package com.bite.forum.service.impl;

import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.dao.UserMapper;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.User;
import com.bite.forum.service.IUserService;
import com.bite.forum.utils.MD5Util;
import com.bite.forum.utils.StringUtil;
import com.bite.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        if(user == null || StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getPassword())
           || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getSalt())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User existsUser = userMapper.selectByUserName(user.getUsername());

        if(existsUser != null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username = " + user.getUsername());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //新用户流程，赋默认值。
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)2);
        user.setState((byte)0);
        user.setDeleteState((byte)0);

        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        int row = userMapper.insertSelective(user);

        if(row != 1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        log.info(ResultCode.SUCCESS.toString());

    }

    @Override
    public User selectByUserName(String username) {
        //参数校验你
        if(StringUtil.isEmpty(username)){

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        User user = userMapper.selectByUserName(username);
        return user;
    }

    @Override
    public User login(String username, String password) {
        //参数校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        User user = selectByUserName(username);

        if(user == null){
            //参数校验
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }

        String encryptPassword = MD5Util.md5Salt(password , user.getSalt());

        if(!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.info(encryptPassword);
            //参数校验
            log.warn(ResultCode.FAILED_LOGIN.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        return user;
    }

    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addArticleCountById(Long id) {
        if(id == null){
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        User user = userMapper.selectByPrimaryKey(id);

        if(user == null){
            // 打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subArticleCountById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        User user = userMapper.selectByPrimaryKey(id);

        if(user == null || user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        User updateuser = new User();
        updateuser.setId(user.getId());
        updateuser.setArticleCount(user.getArticleCount() - 1);

        int row = userMapper.updateByPrimaryKeySelective(updateuser);

        if(row <= 0){
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        log.info(ResultCode.SUCCESS.toString());
    }

    @Override
    public void modifyInfo(User user) {
        if(user == null || user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        //校验是否存在
        if(existsUser == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        int checkAttr = 1;
        //  定义一个专门用来更新的对象，防止用户传入的User对象设置了其他的属性
        // 当使用动态SQL进行更新的时候，覆盖了没有经过校验的字段
        User updateUser = new User();
        //  设置用户Id
        updateUser.setId(user.getId());

        if(!StringUtil.isEmpty(user.getUsername()) &&
           !user.getUsername().equals(existsUser.getUsername())){

            //唯一性校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {

                log.info("username校验失败");
                // 用户已存在
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                // 抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = 0;
        }
        //  校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            // 设置昵称
            updateUser.setNickname(user.getNickname());
            // 更新标志位
            checkAttr = 0;
        }
        //  校验性别
        if (user.getGender() != null && user.getGender() != existsUser.getGender()) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            // 更新标志位
            checkAttr = 0;
        }
        //  校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            // 设置邮箱
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            checkAttr = 0;
        }
        //  校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            // 设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            // 更新标志位
            checkAttr = 0;
        }
        //  校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            // 设置电话号码
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            checkAttr = 0;
        }
        //  根据标志位来决定是否可以执行更新
        if (checkAttr == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row <= 0){
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

    }

    @Override
    public void modifyPassword(Long userId, String newPassword, String oldPassword) {
        if(userId == null || userId < 1 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //校验确认的密码是否相等
        User user = userMapper.selectByPrimaryKey(userId);
        String oldencryptPassword = MD5Util.md5Salt(oldPassword , user.getSalt());
        if(!oldencryptPassword.equals(user.getPassword())){
            log.warn(ResultCode.FAILED.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        String salt = UUIDUtil.UUID_32();

        String encryptPassword = MD5Util.md5Salt(newPassword , salt);

        User updateuser = new User();
        updateuser.setId(user.getId());
        updateuser.setSalt(salt);
        updateuser.setPassword(encryptPassword);
        Date date = new Date();
        updateuser.setUpdateTime(date);

        int row = userMapper.updateByPrimaryKeySelective(updateuser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

}































